import 'package:flutter/cupertino.dart';
import 'package:furaha_mkopo/commonTool/fm_time_tool.dart';
import 'package:furaha_mkopo/manager/fm_global_manager.dart';

import '../cache/fm_cache_tool.dart';
import '../manager/fm_device_manager.dart';

class FMNetParamManager {

  FMNetParamManager._privateConstructor();

  static final FMNetParamManager _instance = FMNetParamManager._privateConstructor();

  factory FMNetParamManager() {
    return _instance;
  }

  var baseDomain = "http://47.237.115.152:7006/maryeka";

  Map<String,String> params = {};

  init() async {
    final absence = FMCacheTool.getSessionId();
    final difficulties = await FMDeviceManager().appVersion();
    final letter = await FMDeviceManager().deviceNameplate();
    final evening = await FMDeviceManager().idfv();
    final speedy = await FMDeviceManager().systemVersion();
    final temporary = await FMDeviceManager().idfa();

    final language = await FMDeviceManager().languageCode();

    // TODO 测试数据
    // final difficulties = "1.0.0";
    // final letter = "arm64";
    // final evening = "1B45DB01-AC55-4153-9D03-D29F736D4486";
    // final speedy = "18.3.1";
    // final temporary = "00000000-0000-0000-0000-000000000000";
    // final language = "en";

    params["difficulties"] = difficulties;
    params["letter"] = letter;
    params["evening"] = evening;
    params["speedy"] = speedy;
    params["temporary"] = temporary;
    params["actual"] = language;

    if (absence.isNotEmpty) {
      params["absence"] = absence;
    }
  }

  void setAbsence(String? sessionId) {
    if (sessionId == null || sessionId.isEmpty) return;
    FMCacheTool.saveSessionId(sessionId);
    params["absence"] = sessionId;
  }

  String getDefaultUrlPath(String path) {
    var paramValue = '';

    if (params.isEmpty) {
      init();
    }

    if (params.isNotEmpty) {
      List<String> paramList = [];
      params.forEach((key, value) {
        String encodedValue = Uri.encodeQueryComponent(value.toString());
        paramList.add('$key=$encodedValue');
      });
      paramValue = paramList.join('&');
    }
    return '$path?$paramValue';
  }

  String getWebUrlPath(String path) {
    var paramValue = '';
    if (params.isNotEmpty) {
      List<String> paramList = [];
      params.forEach((key, value) {
        String encodedValue = Uri.encodeQueryComponent(value.toString());
        paramList.add('$key=$encodedValue');
      });
      paramValue = paramList.join('&');
    }

    if (path.contains("?")) {
      return "$path&$paramValue";
    }else {
      return "$path?$paramValue";
    }
  }
}